﻿<%@ WebHandler Language="C#" Class="ZSContainerShiftTeamDispatchHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System.Web.SessionState;
using System.Configuration;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using BusinessRule.Common;

public class ZSContainerShiftTeamDispatchHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSDispatchIBusiness m_DispatchObj = uMESBusinessFactory.instance.GetuLMSDispatchObject();
    uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "InitpageData"://
                    InitpageData(context);
                    break;
                case "GetContainerShiftTeamDispatch": //查询派工任务单信息
                    GetContainerShiftTeamDispatch(context);
                    break;
                case "GetWorkflowStep":
                    GetWorkflowStep(context);
                    break;
                case "GetStepInfo":
                    GetStepInfo(context);
                    break;
                case "GetWorkByTeamId":
                    GetWorkByTeamId(context);
                    break;
                case "SaveStepDispatch":
                    SaveStepDispatch(context);
                    break;
                case "GetStepDispatchWorker":
                    GetStepDispatchWorker(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    private void InitpageData(HttpContext context)
    {
        DataTable teamdt = m_CommonObj.GetTeamByFactoryID(m_UserInfo.FactoryID);
        var result = new uMESProcessResult();
        result.DBTable = teamdt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void GetContainerShiftTeamDispatch(HttpContext context)
    {
        var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var para = new Dictionary<string, string>();
        if (!string.IsNullOrEmpty(dic["ContainerNo"]))
        {
            para.Add("ContainerNo", dic["ContainerNo"]);
        }
        if (!string.IsNullOrEmpty(dic["MachineStart"]))
        {
            para.Add("MachineStart", dic["MachineStart"]);
        }
        if (!string.IsNullOrEmpty(dic["MachineEnd"]))
        {
            para.Add("MachineEnd", dic["MachineEnd"]);
        }
        if (!string.IsNullOrEmpty(dic["ProductName"]))
        {
            para.Add("ProductName", dic["ProductName"]);
        }
        if (!string.IsNullOrEmpty(dic["MfgOrderName"]))
        {
            para.Add("MfgOrderName", dic["MfgOrderName"]);
        }
        para.Add("WorkCenter", m_UserInfo.WorkCenter);
        para.Add("WorkCenterID", m_UserInfo.WorkCenterID);
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("ShiftID", m_UserInfo.ShiftID.ToString());
        para.Add("Role", "Team");
        para.Add("DispatchStatus", dic["DispatchStatus"]);
        para.Add("PageSize", dic["pageSize"]);
        para.Add("CurrentPageIndex", dic["currentPage"]);
        var result = m_DispatchObj.GetNewZSContainerInfo(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void GetWorkflowStep(HttpContext context)
    {
        var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var para = new Dictionary<string, string>();
        para.Add("WorkflowID", dic["WORKFLOWID"]);
        para.Add("ContainerID", dic["CONTAINERID"]);
        DataTable dt_Workflowstep = m_CommonObj.GetWorkFlowSetpsByWorkflowIDandContainerID(para);
        var result = new uMESProcessResult();
        result.DBTable = dt_Workflowstep;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void GetStepInfo(HttpContext context)
    {
        var workflowStepIDs = "WS.WORKFLOWSTEPID IN ('" + context.Request["data"].ToString().Replace(",", "','") + "')";
        var ContainerID = context.Request["ContainerID"].ToString();
        DataTable StepInfodt = m_CommonObj.GetStepInfo_InfoByWorkflowStepIDs(workflowStepIDs, ContainerID, "", "0", true);
        var result = new uMESProcessResult();
        result.DBTable = StepInfodt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }


    private void GetWorkByTeamId(HttpContext context)
    {
        var teamID = context.Request["teamID"].ToString();
        DataTable StepInfodt = m_CommonObj.GetEmployeeInfoByTeamId(teamID);
        var result = new uMESProcessResult();
        result.DBTable = StepInfodt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void SaveStepDispatch(HttpContext context)
    {
        var container = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["container"].ToString());
        DataTable StepInfo = JsonConvert.DeserializeObject<DataTable>(context.Request["StepInfo"].ToString());
        DataTable Workers = JsonConvert.DeserializeObject<DataTable>(context.Request["Workers"].ToString());
        int selectWorkercount = Workers.Rows.Count; //Convert.ToInt32(context.Request["selectWorkercount"].ToString());
        var dispatch = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["dispatch"].ToString());
        int dispatchcount = 0;
        var result = new uMESProcessResult();
        if (!StepInfo.Columns.Contains("lastSelectWorkerIDs")) 
        {
            StepInfo.Columns.Add("lastSelectWorkerIDs");
        }
        foreach (DataRow row in StepInfo.Rows)
        {
            if (!string.IsNullOrWhiteSpace(row["DispatchFullName"].ToString()))
            {
                result.Message = "工序:" + row["WorkflowStepName"].ToString() + " 工步:" + row["STEPINFONAME"].ToString() + " 已派工";
                break;
            }
            //如果没有选择员工，则继承上一次派工员工信息
            if (selectWorkercount == 0)
            {
                DataTable dt = GetLastDispatchInfo(row, container);
                if (dt.Rows.Count > 0)
                {
                    string lastSelectWorkerIDs = string.Empty;
                    foreach (DataRow dr_ in dt.Rows)
                    {
                        lastSelectWorkerIDs += "," + dr_["WORKERID"].ToString();
                    }
                    row["lastSelectWorkerIDs"] = lastSelectWorkerIDs.Substring(1);
                }
                else
                {
                    result.Message = "工序:" + row["WorkflowStepName"].ToString() + " 工步:" + row["STEPINFONAME"].ToString() + " 没有可以继承的上一次派工员工信息";
                    break;
                }
            }
            else
            {
                row["lastSelectWorkerIDs"] = "";
            }
            //不再验证工序没有工步不能派工的验证
            dispatchcount += 1;
        }

        if (dispatchcount > 0)
        {
            foreach (DataRow row in StepInfo.Rows)
            {
                var dto = new ContainerStepDispatchDTO();
                dto.ContainerID = container["CONTAINERID"];
                dto.FactoryID = m_UserInfo.FactoryID;
                dto.WorkCenterID = m_UserInfo.WorkCenterID;
                dto.TeamID = m_UserInfo.TeamID;
                dto.ResourceID = "";
                dto.WorkerID = "";// '全部操作员存储在派工子表中
                dto.Qty = 1;
                dto.PlannedStartDate = Convert.ToDateTime(dispatch["startDate"]);
                dto.PlannedFinishDate = Convert.ToDateTime(dispatch["endDate"]);
                dto.ContainerStepDispatchID = System.Guid.NewGuid().ToString();
                dto.EmployeeID = m_UserInfo.EmployeeID;
                dto.CreateDate = System.DateTime.Now;
                dto.IsUse = 0;
                dto.PriorityCode = 1;
                dto.WorkflowstepID = row["WorkflowstepID"].ToString();
                if(!string.IsNullOrWhiteSpace(row["StepInfoID"].ToString()))
                {
                    dto.stepID = row["StepInfoID"].ToString();
                }
                if (m_DispatchObj.AddContainerStepDispatchInfo(dto))
                {
                    if (!string.IsNullOrWhiteSpace(row["lastSelectWorkerIDs"].ToString()))
                    {
                        var lastSelectWorkerIDs = row["lastSelectWorkerIDs"].ToString().Split(',');
                        foreach (string lastSelectWorkerID in lastSelectWorkerIDs)
                        {
                            if (!m_DispatchObj.AddDispatchdetails(dto.ContainerStepDispatchID, lastSelectWorkerID, true))
                            {
                                result.Message = row["WorkflowStepName"].ToString() + " 派工添加 继承员工失败";
                                break;
                            }
                        }
                    }
                    else
                    {
                        foreach (DataRow worker in Workers.Rows)
                        {
                            if (!m_DispatchObj.AddDispatchdetails(dto.ContainerStepDispatchID, worker["employeeid"].ToString(), true))
                            {
                                result.Message = row["WorkflowStepName"].ToString() + " 派工添加" + worker["fullname"] + "失败";
                                break;
                            }
                        }
                    }
                }
                else {
                    result.Message = row["ContainerName"].ToString() + " 派工失败";
                    break;
                }
            }
        }


        result.Result = string.IsNullOrWhiteSpace(result.Message);
        result.Message=result.Result?"派工成功":result.Message;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取上一次派工的信息
    /// </summary>
    /// <param name="uldr">工序表列</param>
    /// <param name="row">任务单表列</param>
    /// <returns></returns>
    private DataTable GetLastDispatchInfo(DataRow uldr, Dictionary<string, string> row)
    {
        var para = new Dictionary<string, string>();
        para.Add("machinepname", row["MACHINENAME"].ToString());
        string workflowinfo = row["WORKFLOWNAME"].ToString();
        para.Add("workflowname", workflowinfo.Substring(0, workflowinfo.IndexOf(":")));
        para.Add("productname", row["PRODUCTNAME"].ToString());
        para.Add("workflowstepname", uldr["workflowstepname"].ToString());
        if (!string.IsNullOrWhiteSpace(uldr["StepInfoID"].ToString()))
        {
            para.Add("stepinfodesc", uldr["StepInfoName"].ToString());
            para.Add("stepinfoname", uldr["StepInforeallName"].ToString());
        }
        return m_DispatchObj.GetZSLastDispatchInfo(para);
    }
    /// <summary>
    /// 查询已派工人员信息
    /// </summary>
    /// <param name="context"></param>
    private void GetStepDispatchWorker(HttpContext context) 
    {
        var container = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["container"].ToString());
        DataTable StepInfo = JsonConvert.DeserializeObject<DataTable>(context.Request["StepInfo"].ToString());
        var result = new uMESProcessResult();
        if (!string.IsNullOrWhiteSpace(StepInfo.Rows[0]["CONTAINERSTEPDISPATCHID"].ToString())) 
        {
            result.DBTable = m_DispatchObj.GetDispatchdetails(StepInfo.Rows[0]["CONTAINERSTEPDISPATCHID"].ToString(), true);
        }
        else
        {
            result.DBTable = GetLastDispatchInfo(StepInfo.Rows[0], container);
        }
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
}